package com.rpoonolly.simplegame.mapio.jsoncoders;

import java.io.IOException;

import org.json.simple.JSONObject;

import com.rpoonolly.simplegame.textures.TextureFileDescriptor;
import com.rpoonolly.simplegame.textures.TextureId;

public class TextureIdJSONCoder extends JSONCoder<TextureId> {
	private static TextureIdJSONCoder singletonInstance;
	private TextureFileDescriptorJSONCoder textFileCoder = TextureFileDescriptorJSONCoder.getInstance();
	
	private TextureIdJSONCoder() {}

	public static TextureIdJSONCoder getInstance() {
		if (singletonInstance == null) {
			singletonInstance = new TextureIdJSONCoder();
		}

		return singletonInstance;
	}

	@SuppressWarnings("unchecked")
	@Override
	public JSONObject encode(TextureId obj) throws IOException {
		JSONObject jsonTextId = new JSONObject();
		jsonTextId.put("textureFile", obj.textureFile);
		jsonTextId.put("tileX", obj.tileX);
		jsonTextId.put("tileY", obj.tileY);
		
		return jsonTextId;
	}

	@Override
	public TextureId decode(JSONObject jsonTextId) throws IOException {
		TextureFileDescriptor textFile = (TextureFileDescriptor) textFileCoder.decode((JSONObject) jsonTextId.get("textureFile"));
		int tileX = (Integer) jsonTextId.get("tileX");
		int tileY = (Integer) jsonTextId.get("tileY");
		
		return new TextureId(textFile, tileX, tileY);
	}
}
